package com.chezhujie.www.service;


import com.chezhujie.www.domain.Czjcomments;
import com.chezhujie.www.domain.CzjcommentsPic;
import com.chezhujie.www.domain.CzjcommentsVideo;
import com.chezhujie.www.enums.Approvestatus;
import com.xy.core.utils.Fileupload;
import com.xy.core.utils.PngConverter;
import com.xy.core.utils.UUIDUtils;
import com.xy.user.base.service.BaseService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

/**
 * Created by 汤伟杰 on 2017/6/2.
 */
@Service
public class ApitwjService extends BaseService {
    @Autowired
    private CzjcommentsService czjcommentsService;
    @Autowired
    private CzjcommentsPicService czjcommentsPicService;
    @Autowired
    private CzjcommentsVideoService czjcommentsVideoService;
    @Autowired
    private CzjactivityService czjactivityService;
    @Autowired
    private CzjactdetailService czjactdetailService;
    @Autowired
    private CzjorderdetailService czjorderdetailService;
    @Autowired
    private CzjorderService czjorderService;
    @Autowired
    private CzjorderdistributionService czjorderdistributionService;
    @Autowired
    private CzjfestivalactService czjfestivalactService;
    @Autowired
    private CzjcommodityService czjcommodityService;
    @Autowired
    private CzjdeliveryaddService czjdeliveryaddService;
    @Autowired
    private CzjdataresourceService czjdataresourceService;
    @Autowired
    private CzjtordermemberService czjtordermemberService;
    @Autowired
    private CzjtordermemberdetailService czjtordermemberdetailService;
    @Autowired
    private CzjshopcarService czjshopcarService;
    @Autowired
    private CzjawardapiService czjawardapiService;
    @Autowired
    private CzjpayorderService czjpayorderService;
    @Autowired
    private CzjcarelaService czjcarelaService;



    public void saveCommentsBy(Integer joinlpk, List<MultipartFile> vidfiles, List<MultipartFile> picfiles,
                               String objectId, String content, int type, int userinfoId, HttpServletRequest req) throws Exception {
        Czjcomments czjcomments = setComments(joinlpk,content, objectId,type,userinfoId);//获取评论
        czjcommentsService.checkEntity(czjcomments);

        List<CzjcommentsPic> listPicfile = setCommentsPicfile(picfiles,czjcomments.getCommentsId(),req);//获取上传图片集合
        for (CzjcommentsPic pic : listPicfile) {
            czjcommentsPicService.checkEntity(pic);
        }

        List<CzjcommentsVideo> listVidfile = setCommentsVidfile(vidfiles,czjcomments.getCommentsId(),req);//获取上传视频集合
        for (CzjcommentsVideo video : listVidfile) {
            czjcommentsVideoService.checkEntity(video);
        }



        if(listPicfile.size()!=0){
            String basePath = req.getSession().getServletContext().getRealPath("");
            //缩略图处理
//            for (int i = 0; i < listPicfile.size(); i++) {
//                String mediumPic = genernateMediumPic("/upload/comments/pic/",basePath,listPicfile.get(i).getPicPath(),listPicfile.get(i).getCommentsId());
//                listPicfile.get(i).setPicPath(mediumPic);
//            }
            czjcommentsPicService.saves(listPicfile);
        }
        if(listVidfile.size()!=0){

            czjcommentsVideoService.saves(listVidfile);
        }

        czjcommentsService.insert(czjcomments);




    }

    /**
     * 生成小图
     * @param path /upload/comments/pic/
     * @param basePath linux 路径（服务器路径）
     * @param resourcePicPath   源文件 /upload/..../#{id}-time.png(*image)
     * @param id
     * @return
     */
    private String genernateMediumPic(String path,String basePath, String resourcePicPath,String id) throws FileNotFoundException {
        String longtime = resourcePicPath.substring(resourcePicPath.lastIndexOf("-") + 1, resourcePicPath.lastIndexOf("."));
        String picPath = path+id+"-medium-"+longtime+".jpg";
        try {
            File file = new File(basePath + resourcePicPath);
            BufferedImage coverImg = ImageIO.read(file);

            BufferedImage background = PngConverter.removeTransparent(coverImg);

            Thumbnails.of(background).scale(1f).outputFormat("jpg")
                    .toFile(basePath+picPath);//中等图



            return picPath;
        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;

    }
    public String genernateMediumPic(String path, HttpServletRequest req, String resourcePicPath, String id) throws FileNotFoundException {
        String basePath = req.getSession().getServletContext().getRealPath("");
        return genernateMediumPic(path, basePath, resourcePicPath,id);
    }

    private List<CzjcommentsVideo> setCommentsVidfile(List<MultipartFile> vidfiles, String commentsId, HttpServletRequest req) throws Exception {
        List<CzjcommentsVideo> list = new ArrayList<CzjcommentsVideo>();
        for (MultipartFile multipartFile : vidfiles) {
            String picPath = setPicPath(commentsId,"/upload/comments/video/",multipartFile,req);
            if(null==picPath){
                continue;//跳过空图片
            }
            CzjcommentsVideo czjcommentsVideo = new CzjcommentsVideo();
            czjcommentsVideo.setCommentsId(commentsId);
            czjcommentsVideo.setPicPath(null);
            czjcommentsVideo.setVideoUrl(picPath);
            czjcommentsVideo.setCommentsVideoId(UUIDUtils.getUUID());
            czjcommentsVideo.setCreateTime(new Date());
            czjcommentsVideo.setApproveStatus(0);
            czjcommentsVideo.setDelFlag(0);
            list.add(czjcommentsVideo);
        }
        return list;
    }


    private List<CzjcommentsPic> setCommentsPicfile(List<MultipartFile> picfiles, String commentsId, HttpServletRequest req) throws Exception {
        List<CzjcommentsPic> list = new ArrayList<CzjcommentsPic>();
        for (MultipartFile multipartFile : picfiles) {
            String picPath = setPicPath(commentsId,"/upload/comments/pic/",multipartFile,req);
            if(null==picPath){
                continue;//跳过空图片
            }
            CzjcommentsPic czjcommentsPic = new CzjcommentsPic();
            czjcommentsPic.setCommentPicId(UUIDUtils.getUUID());
            czjcommentsPic.setCommentsId(commentsId);
            czjcommentsPic.setPicPath(picPath);
            czjcommentsPic.setCreateTime(new Date());
            czjcommentsPic.setApproveStatus(0);
            czjcommentsPic.setDelFlag(0);
            list.add(czjcommentsPic);
        }
        return list;
    }
    private String setPicPath(String id,String dir, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
        if((!multipartFile.isEmpty())&&multipartFile.getSize()>0){
            String basePath = req.getSession().getServletContext().getRealPath("");
            String path = basePath+dir+id+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            Fileupload.createDir(basePath+dir);

            InputStream in = multipartFile.getInputStream();
            FileOutputStream out = new FileOutputStream(path);
            try {
                org.apache.commons.io.IOUtils.copy(in,out);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("上传失败！");
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

            String picPath = "/"+path.replace(basePath, "");
            return picPath;
        }
        return null;
    }

    /**
     *
     *
     * @param joinlpk
     * @param content 评论内容
     * @param objectId 评论对象id
     * @param type 评论对象类别 0是活动 1是商品
     * @param userinfoId
     * @return
     */
    private Czjcomments setComments(Integer joinlpk, String content, String objectId, int type, int userinfoId) {
        Czjcomments czjcomments = new Czjcomments();
        czjcomments.setCommentsId(UUIDUtils.getUUID());
        czjcomments.setObjectType(type);
        czjcomments.setUserinfoId(userinfoId);
        czjcomments.setContent(content);
        czjcomments.setReplyCount(0);
        czjcomments.setLikeCount(0);
        czjcomments.setCreatetime(new Date());
        czjcomments.setObjectId(objectId);
        if(joinlpk==null){
            czjcomments.setJoinlpk(0);
        }else{
            czjcomments.setJoinlpk(joinlpk);
        }
        czjcomments.setApproveStatus(Approvestatus.RUNNING.getIndex());
        return czjcomments;
    }





    /**
     * 保存上传图片或者视频，返回 key=主键，value=图片路径 的结果
     * @param files
     * @param path
     * @param req
     * @return
     */
    public Map<String,String> saveFiles(List<MultipartFile> files, String path, HttpServletRequest req) throws Exception {
        Map<String, String> map = new HashMap<String, String>();

        for (MultipartFile multipartFile : files) {
            String uuid = UUIDUtils.getUUID();
            String picPath = setPicPath(uuid,"/upload/"+path+"/",multipartFile,req);
            if(null==picPath){
                continue;//跳过空图片
            }
            map.put(uuid, picPath);
        }
        return map;
    }




}
